package com.java.netty.nio.netty.heardbeat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;

/**
 * @Author: Dgg
 * @Date: 2022/1/2 23:33
 */
public class MyServer {
	public static void main(String[] args) {
		EventLoopGroup boosGroup = new NioEventLoopGroup(1);
		EventLoopGroup workerGroup = new NioEventLoopGroup(8);
		try {
			ServerBootstrap serverBootstrap = new ServerBootstrap();
			serverBootstrap.group(boosGroup, workerGroup)
					.channel(NioServerSocketChannel.class)
					.handler(new LoggingHandler(LogLevel.INFO))//在bossgroup 增加 日志处理器
					.childHandler(new ChannelInitializer<SocketChannel>() {
						@Override
						protected void initChannel(SocketChannel ch) throws Exception {
							ChannelPipeline pipeline = ch.pipeline();
							//加入一个netty 提供的IdlestateHanlder
							/**
							 * netty 提供的空闲状态处理器
							 * long readerIdleTime : 表示多久没有读，就会发送一个检测包检测是否链接
							 * writerIdleTime : 表示多久没有写，就会发送一个检测包检测是否链接
							 * allIdleTime ：  表示多久没有读写，就会发送一个检测包检测是否链接
							 *当idlestateEvent 触发后将会传递给管道的下一个handler去处理
							 * 通过调用下一个handler的userEventTiggered 在该方法中 去处理IdLestateEvent 事件(读空闲，写空闲，读写空闲)
							 */
							pipeline.addLast(new IdleStateHandler(3, 5, 7));
							pipeline.addLast(new MyServerHandler());

						}
					});
			ChannelFuture sync = serverBootstrap.bind(7000).sync();
			sync.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			boosGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}
}
